const BASE_URL = "https://shs.wh33.cn/api/";
import {toast} from '../utils/Tools'
const app = getApp()

export default params => {
  const routeLen = getCurrentPages().length-1
  const {route} =  getCurrentPages()[routeLen]
  // const license = wx.getStorageSync('wechatUser');
  //  判断有没有授权 并且 当前页面是不是首页
  // if(!license && route !== 'pages/home/home/index'){
  //   toast('您还未授权,请先授权')
  //   wx.switchTab({
  //     url: '/pages/home/home/index'
  //   });
  //   return;
  // }
  if(!wx.getStorageSync('token')){
    toast('您还未登录,请先登录')
    wx.reLaunch({
      url: 'pages/index/index'
    });
  }
  // wx.showLoading({title: "正在加载中..."})
  let contentType;
  return new Promise((resolve, reject) => {
    //   如果method是小写,把method转为大写后判断
    let way = params.method
    if(params.method) way = params.method.toUpperCase()
    if (way === 'POST') {
      contentType = 'application/x-www-form-urlencoded';
    } else {
      contentType = 'application/json'
    }
    const data = Object.assign({},params.data,{token:wx.getStorageSync('token')})
    const login_status =  wx.getStorageSync('login_status') || 'manager';
    if(login_status === 'manager'){
      wx.request({
        url: BASE_URL + params.url,
        data,
        timeout:30000,
        method: params.method || "POST",
        header:{
          'content-type': contentType
        },
        success:res => {
          if (res.data) {
            /** start 根据需求 接口的返回状态码进行处理 */
            if (res.statusCode === 200) {
              if(res.data.status === 200 || res.data.code !== -1){
                console.log(res.data)
                resolve(res.data)
              }else{
                toast(res.data.message)
                setTimeout(()=>{
                  wx.reLaunch({
                    url: 'pages/index/index'
                  });
                },1500)
                return;
              }
            } else {
              reject(res.data.message); //request failed
            }
            /** end 处理结束*/
          }
        },
        fail: error => {
          reject(error)
        }
      })
      // wx.hideLoading();
      wx.hideNavigationBarLoading() //完成停止加载图标
      wx.stopPullDownRefresh()
    }
  })
}

export {
  BASE_URL
}